<script setup lang="ts">
import { onMounted, ref } from 'vue'

const contents = [...Array(10).keys()].map((_, i) => i + 1)
const current = ref(1)
// 不要初始化长度
const sectionRefs = ref<(HTMLElement | null)[]>([])
const mainRef = ref<HTMLElement | null>(null)

function handleClick(id: number) {
  console.log(sectionRefs.value[id - 1])
  // 改变
  //   current.value = id
  sectionRefs.value[id - 1]?.scrollIntoView({
    behavior: 'smooth'
  })
}

let observer: IntersectionObserver
onMounted(() => {
  if (mainRef.value && sectionRefs.value) {
    console.log('see it')
    console.log(mainRef.value)
    observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            console.log(e.target.textContent + '进入区域')
            console.log(e.target.id)
            const { id } = e.target
            current.value = parseInt(id)
          } else {
            console.log(e.target.textContent + '离开区域')
          }
        })
      },
      {
        root: mainRef.value,
        threshold: 0, // 当rootMargin设置为-50%的时候，相当于上下已经挤成一条线了，所以只要相交一点即可设置为0
        rootMargin: '-50% 0px'
      }
    )
    if (sectionRefs.value.length > 0) {
      sectionRefs.value.forEach((section) => observer.observe(section!))
    }
  }
})
</script>

<template>
  <div class="toc-basic__container">
    <ul class="toc">
      <li
        v-for="c in contents"
        :key="c"
        :class="{ highlight: c === current }"
        @click="handleClick(c)"
      >
        {{ c }}
      </li>
    </ul>
    <main ref="mainRef" class="content">
      <section
        ref="sectionRefs"
        v-for="c in contents"
        :key="c"
        :id="c.toString()"
        :class="{ highlight: c === current }"
      >
        Section[{{ c }}]
      </section>
    </main>
  </div>
</template>
<style lang="scss" scoped>
.toc-basic__container {
  /* background-color: antiquewhite; */
  height: 100%;
  width: 100%;
  display: flex;
  .toc {
    position: sticky;
    top: 0;
    list-style: none;
    margin: 0;
    padding: 0;
    /* background-color: aqua; */
    li {
      padding: 16px 48px;
      background-color: #fff;
      border: 1px solid black;

      &:hover {
        background-color: #c7c6c6;
      }

      &.highlight {
        background-color: black;
        color: #fff;
      }
    }
  }

  .content {
    flex: 1;
    background-color: aliceblue;
    height: 100%;
    overflow-y: auto;
    section {
      border: 1px solid black;
      background-color: #fff;
      height: 80%;
      display: grid;
      place-items: center;

      &.highlight {
        background-color: lightblue;
        color: #fff;
        font-size: 30px;
      }
    }
  }
}
</style>
